#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安装本地区块链SDK的脚本
用于安装项目中包含的chainmaker和xuper SDK
"""

import os
import subprocess
import sys

def run_command(command, description):
    """执行命令并处理错误"""
    print(f"\n正在{description}...")
    print(f"执行命令: {command}")
    
    try:
        result = subprocess.run(command, shell=True, check=True, 
                              capture_output=True, text=True)
        print(f"✓ {description}成功")
        if result.stdout:
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ {description}失败")
        print(f"错误信息: {e.stderr}")
        return False

def install_local_sdks():
    """安装本地SDK包"""
    print("开始安装本地区块链SDK...")
    
    # 获取项目根目录
    project_root = os.path.dirname(os.path.abspath(__file__))
    
    # SDK路径
    chainmaker_path = os.path.join(project_root, "doc", "chainmaker-sdk-python-master")
    xuper_path = os.path.join(project_root, "doc", "xuper-python-sdk-master")
    
    success_count = 0
    total_count = 2
    
    # 安装chainmaker SDK
    if os.path.exists(chainmaker_path):
        command = f"pip install -e \"{chainmaker_path}\""
        if run_command(command, "安装ChainMaker SDK"):
            success_count += 1
    else:
        print(f"✗ ChainMaker SDK路径不存在: {chainmaker_path}")
    
    # 安装xuper SDK
    if os.path.exists(xuper_path):
        command = f"pip install -e \"{xuper_path}\""
        if run_command(command, "安装XuperChain SDK"):
            success_count += 1
    else:
        print(f"✗ XuperChain SDK路径不存在: {xuper_path}")
    
    # 总结
    print(f"\n安装完成: {success_count}/{total_count} 个SDK安装成功")
    
    if success_count == total_count:
        print("✓ 所有本地SDK安装成功!")
        return True
    else:
        print("⚠ 部分SDK安装失败，请检查错误信息")
        return False

if __name__ == "__main__":
    print("区块链中间件项目 - 本地SDK安装脚本")
    print("=" * 50)
    
    success = install_local_sdks()
    
    if success:
        print("\n接下来可以运行以下命令启动项目:")
        print("python app.py")
        sys.exit(0)
    else:
        print("\n请解决上述错误后重新运行此脚本")
        sys.exit(1)